//
//  HomeViewController.swift
//  DSWeibo
//
//  Created by J on 16/2/21.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit


let  HomeTableViewControllerCell = "HomeTableViewControllerCell"
class HomeTableViewController: BaseTableViewController {
    var statuses :[Statuses]?{
        didSet{
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        //注册2种cell
        
        tableView?.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusTableViewCellIDentifier.NorMalCell.rawValue)
        tableView?.registerClass(RetweetStatusCell.self, forCellReuseIdentifier: StatusTableViewCellIDentifier.retweetCell.rawValue)
        
        

        tableView?.separatorStyle = UITableViewCellSeparatorStyle.None
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension;
        //1.如果没有登陆,就设置未登陆界面的信息
        if !userLogin{
            visitorView?.setUpVisitorView(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜")
        }
        
        //2.初始化导航条
        setUpNav()
        
        //注册通知监听菜单
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: XMGPopoverAnimationWillShow, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: XMGPopoverAnimationWillDismiss, object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.didSelected), name: StatusTableViewPictureViewSelected, object: nil)

        
        //4.添加下拉刷新控件
        
        
        refreshControl = HomeRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: UIControlEvents.ValueChanged)
//        refreshControl?.endRefreshing()
        //加载数据
        loadData()
    }
    
    
    //九宫格图片点击
    func didSelected(noti:NSNotification){
     
//        print(noti.userInfo)
        //注意 如果通过通知传递数据 一定要判断数据是否存在
        guard let _ = noti.userInfo![StatusTableViewPictureViewIndexKey] else {
            print( "没有indexPath")
            return
        }
        
        guard let _ = noti.userInfo![StatusTableViewPictureViewURLKey] else {
            print( "没有配图数组")
            return
        }
        
        
        //创建图片浏览器
        let index = (noti.userInfo![StatusTableViewPictureViewIndexKey] as! NSIndexPath).item
        let urls  = noti.userInfo![StatusTableViewPictureViewURLKey]    as! [NSURL]
 
        
        let vc = photoBrowserController(index: index, urls: urls)
        //present图片浏览器
        presentViewController(vc, animated: true) { 
            
        }
    }
    
    
    //修改标题按钮状态
    func change(){
        
        let titlButton = navigationItem.titleView as!TitleButton
        titlButton.selected = !titlButton.selected
    }
    
    
    //是否上拉
    var pullupRefreshFlag = false
    //如果想调用一个私有方法
//    1.去掉private
//    2.@objc 当作OC方法处理
    
    
    @objc private func loadData(){
        
      //默认当作下拉处理
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        //判断是否是上拉
        
        if pullupRefreshFlag {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        
        
     Statuses.loadStatuses(since_id,max_id: max_id) { (models, error) in
        if error != nil || models?.count <= 0 {
            return
        }
        self.pullupRefreshFlag = false

        self.showNewStatusCount(models!.count)
        if since_id > 0 && models?.count > 0 {//如果不是第一条 数据添加到之前数组前面
            self.statuses = models! + self.statuses!//插入到前面
        }else if max_id > 0{//如果是上拉加载
            self.statuses = self.statuses! + models!//添加到后面
        }else{//如果是下拉刷新 直接赋值
            self.statuses = models
        }
        
        self.refreshControl?.endRefreshing()
        
        }
        
    }
    
    
    private func showNewStatusCount(count:Int){
        
        newStatusLabel.text = (count == 0) ? "没有刷新到新微博数据" : "刷新到\(count)条微博数据"
        
        //1.记录提醒控件frame
        let rect = newStatusLabel.frame
        let duration : Double = 2
        
        //2.执行动画
        UIView.setAnimationRepeatAutoreverses(true)
        UIView.animateWithDuration(duration, animations: {
            
            self.newStatusLabel.transform =  CGAffineTransformTranslate(self.newStatusLabel.transform, 0, rect.size.height*3)
            
        }) { (complete:Bool) in
        
        }
        
        
        
    }
    
    
    //移除通知 对应dealloc
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

  
    private func setUpNav(){
    //1.初始化左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightButtonClick))
        
    //2.初始化标题按钮
    
        let titleBtn = TitleButton()
        navigationItem.titleView = titleBtn
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.TitleButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    
    
    func rightButtonClick(){
        
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        
        let vc = sb.instantiateInitialViewController()!
        presentViewController(vc, animated: true, completion: nil)
    }
    
    func leftButtonClick(){
        
        
    }
    ///标题按钮点击
    func TitleButtonClick(btn:TitleButton){
        
        //1.修改箭头方向
//        btn.selected = !btn.selected
        //2.弹出菜单
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        
        //2.1设置转场代理
        //默认情况下modal会移除之前控制器的view 替换为当前弹出的view
        //如果自定义转场,那么就不会移除之前控制器的view
        vc?.transitioningDelegate = popoverAnimator
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
      

        //2.2设置转场的样式
        presentViewController(vc!, animated: true, completion: nil)
    }
    

    
    //MARK:懒加载
    //以ID那个要定义一个属性来保存自定义转场对象 否则会报错
    private lazy var popoverAnimator : PopoverAnimation = {
        
        let pa = PopoverAnimation()
        pa.presentFrame =  CGRect(x:(UIScreen.mainScreen().bounds.width - 200)*0.5,y:60, width: 200, height: 200)

        return pa
        
    }()
    
    //刷新提醒label
    private lazy var newStatusLabel :UILabel = {
       let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        label.textColor     = UIColor.whiteColor()
        let height = 44
        label.frame = CGRect(x: 0, y: -2*height, width: 320, height: height)
        //添加
       self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
    
    
    //微博行高缓存,利用字典作为容器,key作为微博id 值就是对应微博行高
    var rowCache :[Int:CGFloat] = [Int:CGFloat]()

}


extension HomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIDentifier.cellID(status))as! StatusTableViewCell
        //枚举内部判断是否是转发cell
        
        cell.status = status;
//        print(#function)
        
        
        //判断是否滚动到了最后一个cell
        let count = statuses!.count ?? 0
        if  indexPath.row == count-1 {
            pullupRefreshFlag = true
            loadData()

        }
        
        
        return cell
    }
    
//    var rowCache : NSCache?
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //1.取出对应行模型
        let status = statuses![indexPath.row]
        //判断缓存中跟有没有
        if  let height = rowCache[status.id]{
//            print("从缓存中获取高度")
            return height
        }
        //2.拿到对应cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIDentifier.cellID(status))as! StatusTableViewCell
        //3.
        let rowHeight = cell.rowHeight(status)
        //5.缓存行高
//        rowCache[status.id] = rowHeight
        //6.返回行高
//        print("重新计算 高度")

//        print(#function)
        
        return rowHeight
    }

    override func didReceiveMemoryWarning() {
        //清空缓存
        rowCache.removeAll()
    }
    
}
